<template>
  <div>
    <FormPanel ref="formPanel" :list="formList" :cols="1" :labelWidth="110" :collapse="false" :isSubmitBtn="false" @formChange="formChangeHandle"></FormPanel>
    <BaseDialog :visible.sync="selectAssign" :title="'派工'" destroyOnClose width="300px" :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <selectAssignModel @close="closeSelectAssign" />
    </BaseDialog>
    <br />
    <div style="text-align:center;">
      <el-button size="small" type="primary" :loading="isLoading" @click="saveDialog">确定</el-button>
      <el-button size="small" type="primary" @click="closePage">取消</el-button>
    </div>
  </div>
</template>

<script>
import { getWorkAllGroup, getAllUserByWorkGroupId } from '@/api/repair/repairAssign/repairAssign';
import { dictionary } from '@/utils/dictMixin';
import { saveAssign, queryR, selectWorkGroupDicts, queryWorker } from '@/api/repair/repairAssign/repairAssign';
import { searchRoleByCode, searchRoleByCodes } from '@/api/common/empSelect/index';
import dictCode from '@/utils/dictCode';
import moment from 'moment';
import selectAssignModel from './selectAssignModel';
import pinyin, { STYLE_FIRST_LETTER } from '@/components/Pinyin/index';
import { getAllUser, getGroupList, getWorkGroupNameByWorkId } from '@/api/repair/queryStatistics/queryAccounts';
export default {
  name: 'addAssignModel',
  components: {
    selectAssignModel
  },
  mixins: [dictionary],
  props: ['LabourColumns', 'manhour', 'Type', 'rotime', 'assignType', 'allUsers'],
  data() {
    this.saveData = null;
    return {
      fetchParams: {},
      selectAssign: false,
      formList: this.assignType === 'group' ? this.createGroupTopFilterList() : this.createTopFilterList(),
      technicianRes: [], // 所有的技师
      allWorkGroup: [], // 所有的班组
      filterUsers: [], // 通过班组id获取到的技师
      copyFilterUsers: [],
      technicianModel: '',
      isLoading: false
    };
  },
  created() {
    // if (this.assignType === 'group') {
    //   // group-派工到班组，
    //   this.formList = this.createGroupTopFilterList();
    // }
    if (this.assignType === 'group') {
      this.getWorkAllGroups(); // 获取所有班组
    }
    console.log(this.formList, 'formList');
  },
  mounted() {
    // console.log(this.LabourColumns,"主页面带入的值")
    // console.log(this.rotime,"工单的开工时间")
    this.fen();
    this.serviceConsultant();

    if (this.Type == 'edit') {
      console.log(this.LabourColumns, 'this.LabourColumns');
      this.formList.find(item => item.fieldName === 'assignLabourhour').initialValue = this.LabourColumns[0].ASSIGN_LABOUR_HOUR;
      if (this.assignType === 'group') {
        let workGroupCode = this.formList.find(item => item.fieldName === 'workGroupCode');
        workGroupCode && (workGroupCode.initialValue = this.LabourColumns[0].WORKGROUP_CODE || '');
        let technician = this.formList.find(item => item.fieldName === 'technician');
        let technicianItem = this.allUsers.find(x => x.value == this.LabourColumns[0].TECHNICIAN);
        console.log(technicianItem);
        // technician && (technician.initialValue = this.LabourColumns[0].TECHNICIAN || '');
        technician && (this.technicianModel = this.LabourColumns[0].TECHNICIAN || '');
        technicianItem && (this.technicianModel = technicianItem.text);
        const pId = this.LabourColumns[0].WORKGROUP_ID;
        if (pId) {
          this.resetTechnician(pId);
        }
      } else {
        let technician = this.formList.find(item => item.fieldName === 'technician');
        // technician && (technician.initialValue = this.LabourColumns[0].TECHNICIAN || '');
        technician && (this.technicianModel = this.LabourColumns[0].TECHNICIAN || '');
        let technicianItem = this.allUsers.find(x => x.value == this.LabourColumns[0].TECHNICIAN);
        technicianItem && (this.technicianModel = technicianItem.text);
      }
      this.getqueryR();
    } else {
      this.$refs.formPanel.RESET_FORM();
    }
  },
  methods: {
    async getWorkAllGroups() {
      let res = await getWorkAllGroup();
      console.log(res.data, 'getWorkAllGroup');
      this.banzuList = res.data.map(x => ({ value: x.WORKGROUP_CODE, text: `${x.WORKGROUP_CODE} - ${x.WORKGROUP_NAME}`, Id: x.WORKGROUP_ID }));
      let workGroupCode = this.formList.find(x => x.fieldName === 'workGroupCode');
      workGroupCode.itemList = this.banzuList;
      console.log(this.banzuList, 'this.banzuList');
      // this.formList.find(x => x.fieldName === 'workGroupCode').itemList = this.allWorkGroup; // 车间需要根据id获取名称
      // if (workGroupCode.initialValue) {
      //   const pId = this.banzuList.find(x => x.value === workGroupCode.initialValue).Id;
      //   if (pId) {
      //     this.resetTechnician(pId);
      //   }
      // }
    },
    async resetTechnician(val) {
      let res = await getAllUserByWorkGroupId({ workGropId: val, userId: '', sign: 'work' });
      if (res.resultCode === 200) {
        let personList = res.data.map(x => ({ value: x.USER_ID, text: `${x.EMPLOYEE_NAME}` }));
        this.filterUsers = personList;
        this.copyFilterUsers = [...personList];
        console.log('personList', personList);
      }
    },
    filterMethod(queryString) {
      console.log(queryString);
      if (!queryString.length) {
        this.filterUsers = this.copyFilterUsers;
        return;
      }

      let res = [];
      this.filterUsers = this.copyFilterUsers.filter(x => {
        // 拼音匹配
        const pyStr = _.flatten(pinyin(x.text, { style: STYLE_FIRST_LETTER })).join('');
        // 字符串匹配

        return pyStr.toLowerCase().includes(queryString.toLowerCase()) || x.text.includes(queryString);
      });
      console.log(this.filterUsers);
    },
    createGroupTopFilterList() {
      return [
        {
          type: 'SELECT',
          label: '班组',
          fieldName: 'workGroupCode',
          placeholder: '请选择派工技师或班组',
          filterable: true,
          itemList: [],
          change: (val, text) => {
            this.technicianModel = '';
            if (val) {
              const pId = this.banzuList.find(x => x.value === val).Id;
              console.log('班组pId', pId);
              if (pId) {
                this.resetTechnician(pId);
              }
            }
            if (!val) {
              this.filterUsers = [];
              this.copyFilterUsers = [];
            }
          }
        },
        {
          type: 'SELECT',
          label: '派工技师',
          fieldName: 'technician',
          placeholder: '请选择派工技师或班组',
          filterable: true,
          itemList: [],
          initialValue: '',
          render: props => {
            return (
              <div>
                <el-select v-model={this.technicianModel} placeholder="请选择" filterable filter-method={this.filterMethod}>
                  {this.filterUsers.map(x => {
                    return <el-option value={x.value} key={x.value} label={x.text}></el-option>;
                  })}
                </el-select>
                )
              </div>
            );
          }
        },
        {
          type: 'SELECT',
          label: '派工工位',
          fieldName: 'labourPositionCode',
          placeholder: '请选择派工工位',
          itemList: []
        },
        {
          type: 'INPUT_NUMBER',
          label: '分项工时',
          fieldName: 'assignLabourhour',
          placeholder: '请输入分项工时',
          min: 0
        },
        {
          type: 'INPUT_NUMBER',
          label: '工时系数',
          fieldName: 'labourFactor',
          placeholder: '请输入工时系数',
          initialValue: 100,
          style: { width: 'calc(100% - 90px)' },
          descOptions: {
            content: '%'
          },
          rules: [{ pattern: /^([1-9]\d{0,3}|9999)$/, message: '请输入正整数(最大四位)' }]
        },
        {
          type: 'DATE',
          dateType: 'datetime',
          label: '开工时间',
          fieldName: 'itemStartTime',
          initialValue: moment().format('YYYY-MM-DD HH:mm:ss')
        },
        {
          type: 'DATE',
          dateType: 'datetime',
          label: '预计完工时间',
          fieldName: 'estimateEndTime',
          initialValue: moment().format('YYYY-MM-DD HH:mm:ss')
        }
      ];
    },
    createTopFilterList() {
      return [
        {
          type: 'SELECT',
          label: '派工技师',
          fieldName: 'technician',
          placeholder: '请选择派工技师或班组',
          filterable: true,
          itemList: [],
          initialValue: '',
          render: props => {
            return (
              <div>
                <el-select v-model={this.technicianModel} placeholder="请选择" filterable filter-method={this.filterMethod}>
                  {this.filterUsers.map(x => {
                    return <el-option value={x.value} key={x.value} label={x.text}></el-option>;
                  })}
                </el-select>
                )
              </div>
            );
          }
        },
        {
          type: 'SELECT',
          label: '派工工位',
          fieldName: 'labourPositionCode',
          placeholder: '请选择派工工位',
          itemList: []
        },
        {
          type: 'INPUT_NUMBER',
          label: '分项工时',
          fieldName: 'assignLabourhour',
          placeholder: '请输入分项工时',
          min: 0
        },
        {
          type: 'INPUT_NUMBER',
          label: '工时系数',
          fieldName: 'labourFactor',
          placeholder: '请输入工时系数',
          initialValue: 100,
          style: { width: 'calc(100% - 90px)' },
          descOptions: {
            content: '%'
          },
          rules: [{ pattern: /^([1-9]\d{0,3}|9999)$/, message: '请输入正整数(最大四位)' }]
        },
        {
          type: 'DATE',
          dateType: 'datetime',
          label: '开工时间',
          fieldName: 'itemStartTime',
          initialValue: moment().format('YYYY-MM-DD HH:mm:ss')
        },
        {
          type: 'DATE',
          dateType: 'datetime',
          label: '预计完工时间',
          fieldName: 'estimateEndTime',
          initialValue: moment().format('YYYY-MM-DD HH:mm:ss')
        }
      ];
    },
    fen() {
      this.formList.find(item => item.fieldName === 'assignLabourhour').initialValue = this.manhour;
    },
    formChangeHandle(val) {
      this.saveData = val;
    },
    async saveDialog() {
      if (this.isLoading) return;
      this.isLoading = true;
      let d = new Date(); // 获取当前时间
      let startTime = new Date(this.formList.find(item => item.fieldName === 'itemStartTime').initialValue); // 开工时间
      let endTime = new Date(this.formList.find(item => item.fieldName === 'estimateEndTime').initialValue); // 预计完工时间
      let rotime = new Date(this.rotime); // 工单开单日期
      console.log(startTime, '开始时间', endTime, '结束时间', rotime, '开工单日期', d, '获取当前日期');

      this.saveData = null;
      this.$refs.formPanel.SUBMIT_FORM();
      if (this.saveData != null) {
        // 开工时间不能晚于系统时间,
        // if(startTime>d){
        //    return this.$notify.warning({ title: '提示信息', message: '开工时间不能晚于系统时间' });
        // }
        // 开工日期,不能早于开单时间
        if (startTime < rotime) {
          return this.$notify.warning({ title: '提示信息', message: '开工时间不能早于开单时间' });
        }
        // 预计完工时间不能早于开工时间
        if (endTime < startTime) {
          return this.$notify.warning({ title: '提示信息', message: '预计完工时间不能早于开工时间' });
        }

        const s = {
          tables: this.LabourColumns,
          technician: this.formList.find(item => item.fieldName === 'technician').initialValue,
          labourPositionCode: this.formList.find(item => item.fieldName === 'labourPositionCode').initialValue,
          workGroupCode: this.formList.find(item => item.fieldName === 'workGroupCode') ? this.formList.find(item => item.fieldName === 'workGroupCode').initialValue : '',
          assignLabourHour: this.formList.find(item => item.fieldName === 'assignLabourhour').initialValue,
          labourFactor: this.formList.find(item => item.fieldName === 'labourFactor').initialValue,
          itemStartTime: this.formList.find(item => item.fieldName === 'itemStartTime').initialValue,
          estimateEndTime: this.formList.find(item => item.fieldName === 'estimateEndTime').initialValue
        };
        // if (this.assignType === 'group') {
        s.technician = this.technicianModel;
        if (this.Type == 'edit') {
          // 回显是直接使用name（相当于直接翻译过了，如果离职人员，下拉中是不包含的，无法翻译），
          // 下拉选择是使用userId，上传后台都是通过id
          // 通过name如果找到对应的iuserId就换成id，否则就都当成id处理（回显的时候，需要显示离职人员。离职人员）
          let item = this.allUsers.find(x => x.text == this.technicianModel);
          item && (s.technician = item.value);
        }
        // }
        let res = await saveAssign(s).then(res => {
          console.log('saveAssign');
          this.isLoading = false;
          if (res.resultCode === 200) {
            // this.$notify({ title: '提示信息', message: '派工操作成功', type: 'success' });
            this.isLoading = true;
            this.$emit('close', 'save');
          }
        });
      } else {
        this.isLoading = false;
        return this.$notify.warning({ title: '提示信息', message: '有校验信息未通过' });
      }
    },
    async getqueryR() {
      let res = await queryR(this.LabourColumns[0].ASSIGN_ID);
      console.log(res, 'lll');
      this.formList.find(item => item.fieldName === 'technician').initialValue = res.data.TECHNICIAN;
      this.formList.find(item => item.fieldName === 'labourPositionCode').initialValue = res.data.LABOUR_POSITION_CODE;
      // this.formList.find(item => item.fieldName === 'workerTypeCode').initialValue = res.data.WORKER_TYPE_CODE;
      this.formList.find(item => item.fieldName === 'assignLabourhour').initialValue = res.data.ASSIGN_LABOUR_HOUR;
      this.formList.find(item => item.fieldName === 'labourFactor').initialValue = parseInt(res.data.LABOUR_FACTOR * 100);
      console.log('+++++++++++++++++++++++++++++++' + res.data.LABOUR_FACTOR);
      this.formList.find(item => item.fieldName === 'itemStartTime').initialValue = res.data.ITEM_START_TIME;
      this.formList.find(item => item.fieldName === 'estimateEndTime').initialValue = res.data.ESTIMATE_END_TIME;
    },
    // 售前人员接口数据
    async serviceConsultant() {
      let technician = { role: dictCode.TECHNICIAN }; // 指定技师
      const technicianRes = await searchRoleByCodes(technician);
      console.log(technicianRes.data, 'ppppppppppppp');
      const assignWorkType = await selectWorkGroupDicts();

      this.technicianRes = technicianRes.data.map(x => ({ text: x.employeeName, value: x.userId + '' }));
      if (this.assignType !== 'group') {
        // this.formList.find(item => item.fieldName === 'technician').itemList = this.technicianRes;
        this.filterUsers = this.technicianRes;
        this.copyFilterUsers = [...this.technicianRes];
      }
      this.formList.find(item => item.fieldName === 'labourPositionCode').itemList = assignWorkType.data.map(x => ({ text: x.LABOUR_POSITION_NAME, value: x.LABOUR_POSITION_CODE }));
    },
    closeSelectAssign() {
      this.selectAssign = false;
    },
    closePage() {
      this.$emit('close');
    }
  }
};
</script>
